package com.mvc.com.util;

public class SortAlgorithm {

    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            // pi is partitioning index, arr[pi] is now at right place
            int pi = partition(arr, low, high);

            // Separately sort elements before and after partition
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }

    private static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];    // pivot
        int i = (low - 1);  // Index of smaller element

        int removedInversions = 0; // Number of inversions removed
        int addedInversions = 0;   // Number of inversions added

        for (int j = low; j < high; j++) {
            // If current element is smaller than the pivot
            if (arr[j] < pivot) {
                i++;

                // Swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

                // Calculate removed inversions
                removedInversions += high - j - 1;

                // Calculate added inversions
                addedInversions += i - j - 1;
            }
        }

        // Swap arr[i+1] and arr[high] (or pivot)
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        // Print the number of inversions removed and added
        System.out.println("Removed inversions: " + removedInversions);
        System.out.println("Added inversions: " + addedInversions);

        return i + 1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 9, 8, 7, 6, 5};
        int n = arr.length;
        quickSort(arr, 0, n - 1);
        System.out.println("Sorted array:");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
